#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>

#define FILE_NAME "./IPtest.txt"

float read_speed(const char *file, int flag)
{
	FILE *fp = NULL;
	char *ptr = NULL;
	char *endptr = NULL;
	char *key[3] = {"Average Rate(KB/s):", "Current Rate(KB/s):", "Peak Rate (KB/s):"};
	int  spawn[3] = {strlen(key[0]), strlen(key[1]), strlen(key[2])};
	char info[512] = {0};

	if (sizeof(spawn)/sizeof(int) < flag )
		return 0.1f;

	fp = fopen(file, "r");
	if (!fp)
	{
		printf("fopen fail.\n");
		return 0.0f;
	}

	while(fgets(info, sizeof(info) - 1, fp))
	{
		if (NULL != (ptr = strstr(info, key[flag])))
		{
			endptr = ptr + spawn[flag];
			if (isspace(*endptr))
			{
				endptr++;
			}

			while(isdigit(*endptr))
				endptr++;

			*endptr = 0;
			//printf("[%s:%d] Rate:%s.\n", __FUNCTION__, __LINE__, ptr + spawn[flag]);
			return (float)(8 * atoi(ptr + spawn[flag]))/1024;
		}
		memset(info, 0, sizeof(info));
	}
	fclose(fp);

	return 0.0f;

}

int add(int a, int b)
{
	return (a+b);
}

int dec(int a, int b)
{
	if (b < a)
	return a - b;
	if (a < b)
		return b - a;
}

void dbg_printf()
{
	printf("debug:");
	printf("new line:");
}
void dbg_printf1()
{
	printf("debug:");
	printf("new line:");
	printf("new line:");
}

int main() {
	printf("avg:%f\n", read_speed(FILE_NAME, 0));
	printf("curr:%f\n", read_speed(FILE_NAME, 1));
	printf("peek:%f\n", read_speed(FILE_NAME, 2));
	return 0;
}
